package appcus

import (
	"counter-help/admin/server/global"
	customerRes "counter-help/admin/server/model/app/response"
	"counter-help/admin/server/model/customer"
	"errors"
)

type CusOrderViewService struct{}

// CreateOrderView 创建订单浏览记录
func (cusOrderViewService *CusOrderViewService) CreateOrderView(userID, orderID int) error {
	// 检查订单是否属于当前用户自己
	var order customer.CusOrder
	err := global.GVA_DB.Where("id = ?", orderID).First(&order).Error
	if err != nil {
		return errors.New("订单不存在")
	}
	if order.OrderUserId == userID {
		return nil
	}

	// 检查是否已存在该浏览记录
	var view customer.CusOrderView
	err = global.GVA_DB.Where("user_id = ? AND order_id = ?", userID, orderID).First(&view).Error
	if err == nil {
		// 记录已存在，不进行写入，直接返回 nil
		return nil
	}

	// 如果不存在，则创建新的浏览记录
	newView := customer.CusOrderView{
		UserID:  &userID,
		OrderID: &orderID,
	}

	return global.GVA_DB.Create(&newView).Error
}

// GetOrderViewsByUserID 获取用户的浏览订单记录
func (cusOrderViewService *CusOrderViewService) GetOrderViewsByUserID(userID int) ([]customerRes.CusOrderListResponse, error) {
	var views []customer.CusOrderView
	err := global.GVA_DB.Where("user_id = ?", userID).Find(&views).Error
	if err != nil {
		return nil, err
	}

	var orderIDs []int
	for _, view := range views {
		orderIDs = append(orderIDs, *view.OrderID)
	}

	// 查询所有浏览的订单详细信息，但排除该用户自己发布的订单
	var orders []customer.CusOrder
	err = global.GVA_DB.Where("id IN ? AND order_user_id != ?", orderIDs, userID).Find(&orders).Error
	if err != nil {
		return nil, err
	}

	// 转换为响应格式
	var orderResponses []customerRes.CusOrderListResponse
	for _, order := range orders {
		orderResponses = append(orderResponses, convertCusOrderToResponse(order))
	}

	return orderResponses, nil
}
